#!/usr/bin/env bash

CACHE_DIR="/srv/cache/obs/tar_scm/repo/next/openEuler"
PACKAGE=$1

if [[ ! -d ${CACHE_DIR} ]]; then
    exit "Cache folder not exists ${CACHE_DIR}"
    exit 1
fi

cd ${CACHE_DIR}

if [[ -d "${CACHE_DIR}/${PACKAGE}" ]]; then
    cd ${PACKAGE}
    git pull
    if [ $? -ne 0 ]
    then
        cd ${CACHE_DIR}
        rm -rf ${PACKAGE}
        git clone "https://gitee.com/src-openeuler/${PACKAGE}.git"
    fi
else
    git clone "https://gitee.com/src-openeuler/${PACKAGE}.git"
fi

if [[ $? != 0 ]]; then
    echo "failed to update project ${PACKAGE}"
    echo "${PACKAGE} update failed" | mail -s "gitee_to_obs_failed" 303386771@qq.com
    exit 1;
else
    branchlist=`git branch -a`
    for bc in $branchlist
    do
        branchname=`echo $bc | cut -d "/" -f 3`
        if [ ! -d "/srv/cache/obs/tar_scm/repo/next/${branchname}" ];then
            continue
        fi
        cd /srv/cache/obs/tar_scm/repo/next/${branchname}
        if [ ! -d  ${PACKAGE} ];then
            git clone "https://gitee.com/src-openeuler/${PACKAGE}.git" -b $branchname
        else
            cd ${PACKAGE}
            git pull
            if [ $? -ne 0 ]
            then
                cd ..
                rm -rf ${PACKAGE}
                git clone "https://gitee.com/src-openeuler/${PACKAGE}.git" -b $branchname
            fi
        fi
    done
fi
